package com.daxidi.cn.controller;


import com.daxidi.cn.entity.Notice;
import com.daxidi.cn.mapper.ShopMapper;
import com.daxidi.cn.params.AddBaseImg;
import com.daxidi.cn.params.AddNoticeParam;
import com.daxidi.cn.params.UpdateFileParam;
import com.daxidi.cn.service.INoticeService;
import com.daxidi.cn.utils.FileContextReplace;
import com.daxidi.cn.utils.GenerateHtmlUtils;
import com.daxidi.cn.utils.ReturnResult;
import com.daxidi.cn.utils.ReturnResultUtils;
import com.daxidi.cn.vo.ShopNameVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 工会小程序公告信息表 前端控制器
 * </p>
 *
 * @author wsh
 * @since 2020-12-04
 */
@Log4j
@Api(tags = "公告信息")
@RestController
@RequestMapping("/api/v1/union/notice")
public class NoticeController {

    @Value("${pic.upload.location}")
    private String fileLocation;

    @Value("${pic.upload.sysLocation}")
    private String sysLocation;

    @Value("${file.notice.filePath}")
    private String filePaths;

    @Value("${file.notice.accessPath}")
    private String sysPath;

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private ShopMapper shopMapper;

    @ApiOperation(value = "html 文件上传")
    @PostMapping(value = "/getHtml")
    public ReturnResult getHtml(@RequestBody AddNoticeParam addNoticeParam) {
        try {
            String htmlContent = addNoticeParam.getHtmlContent();
            String path = GenerateHtmlUtils.genHtml(htmlContent);
            HashMap<String, Object> map = new HashMap<>();
            map.put("path", path);
            return ReturnResultUtils.returnSuccess(map);
        } catch (Exception e) {
            log.error("html文件上传失败！" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(661, "html文件上传失败！");
        }
    }

    @ApiOperation(value = "发布公告")
    @ApiResponses({
            @ApiResponse(code = 500, message = "发布失败，数据为空"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PostMapping("/publish")
    public ReturnResult publish(@RequestBody Notice notice) {
        if (ObjectUtils.isEmpty(notice)) {
            return ReturnResultUtils.returnFailMsg(500, "发布失败，数据为空");
        }
        try {
            noticeService.createNotice(notice);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("发布失败" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(501, "发布公告失败！");
        }
    }

    @ApiOperation(value = "下线")
    @ApiResponses({
            @ApiResponse(code = 500, message = "id错误"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PutMapping("/outState/{id}")
    public ReturnResult outState(@PathVariable("id") Integer id) {
        if (null == id || id == 0) {
            return ReturnResultUtils.returnFailMsg(500, "id错误");
        }
        try {
            noticeService.updateState(id);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("公告下线失败！ " + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(502, "公告下线失败！查看公告id是否相符");
        }
    }

    @ApiOperation(value = "上线")
    @ApiResponses({
            @ApiResponse(code = 500, message = "id错误"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PutMapping("/upState/{id}")
    public ReturnResult upState(@PathVariable("id") Integer id) {
        if (null == id || id == 0) {
            return ReturnResultUtils.returnFailMsg(500, "id错误");
        }
        try {

            noticeService.upState(id);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("公告上线失败！ " + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(503, "公告上线失败！查看公告id是否相符");
        }
    }

    @ApiOperation(value = "编辑")
    @ApiResponses({
            @ApiResponse(code = 500, message = "修改失败，数据为空"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PutMapping("/redact")
    public ReturnResult redact(@RequestBody Notice notice) {
        if (ObjectUtils.isEmpty(notice)) {
            return ReturnResultUtils.returnFailMsg(500, "修改失败，数据为空");
        }
        try {
            noticeService.updateNotice(notice);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("修改公告失败！ " + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(504, "修改公告失败！查看公告id是否相符");
        }
    }

    @ApiOperation(value = "置顶")
    @ApiResponses({
            @ApiResponse(code = 500, message = "id错误"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PutMapping("/setTop/{id}")
    public ReturnResult setTop(@PathVariable("id") Integer id) {
        if (null == id || id == 0) {
            return ReturnResultUtils.returnFailMsg(500, "id错误");
        }
        try {
            noticeService.setTop(id);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("置顶公告失败！ " + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(505, "置顶公告失败！查看公告id是否相符");
        }
    }

    @ApiOperation(value = "取消置顶")
    @ApiResponses({
            @ApiResponse(code = 500, message = "id错误"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PutMapping("/cancelTop/{id}")
    public ReturnResult cancelTop(@PathVariable("id") Integer id) {
        if (null == id || id == 0) {
            return ReturnResultUtils.returnFailMsg(500, "id错误");
        }
        try {
            noticeService.cancelTop(id);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("取消置顶公告失败！ " + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(506, "取消置顶公告失败！查看公告id是否相符");
        }
    }

    @ApiOperation(value = "公告列表")
    @ApiResponses({
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @GetMapping("/showAllNotices")
    public ReturnResult showAllNotices(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer limit) {
        try {
            Map map = noticeService.selectAllNotices2(page, limit);
            return ReturnResultUtils.returnSuccess(map);
        } catch (Exception e) {
            log.error("公告列表查询失败！" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(507, "公告列表查询失败！");
        }
    }

    @ApiOperation(value = "公告上线列表查询")
    @ApiResponses({
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @GetMapping("/showAllNotice")
    public ReturnResult showAllNotice(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer limit) {
        try {
            Map map = noticeService.selectAllNotices2(page, limit);
            return ReturnResultUtils.returnSuccess(map);
        } catch (Exception e) {
            log.error("公告上线列表查询失败！" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(508, "公告上线列表查询失败！查看公告id是否相符");
        }
    }

    @ApiOperation(value = "公告下线列表查询")
    @ApiResponses({
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @GetMapping("/showAll")
    public ReturnResult showAll(@RequestParam(defaultValue = "1", required = false) Integer page, @RequestParam(defaultValue = "20", required = false) Integer limit) {
        try {
            Map map = noticeService.selectAll(page, limit);
            return ReturnResultUtils.returnSuccess(map);
        } catch (Exception e) {
            log.error("公告上线列表查询失败！" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(508, "公告上线列表查询失败！查看公告id是否相符");
        }
    }

    @ApiOperation(value = "商家名称下拉框")
    @GetMapping("/showShopName")
    public ReturnResult showShopName() {
        List<ShopNameVo> shopNameVos = shopMapper.showShopName();
        if (shopNameVos != null) {
            return ReturnResultUtils.returnSuccess(shopNameVos);
        } else {
            return ReturnResultUtils.returnFailMsg(500, "商家名称数据为空");
        }
    }

    @ApiOperation(value = "富文本上传图片")
    @PostMapping(value = "/base64ToImg")
    public ReturnResult base64ToImg(@RequestBody AddBaseImg addBaseImg) {
        String img = addBaseImg.getImg();
        String imgPath = addBaseImg.getImgPath();
        BASE64Decoder decoder = new BASE64Decoder();
        //Base64解码
        byte[] b = new byte[0];
//        //图片完整路径 注意：目录下一定要加一个文件格式不然图片字节输出不了
//        String fileName = GenerateHtmlUtils.getRandomString() + String.valueOf(System.currentTimeMillis()).substring(6);
//        String path = fileLocation + fileName + ".png";
        try {
            String replace = img.substring(0, img.indexOf(",") + 1);
            img = img.replace(replace, "");
            b = decoder.decodeBuffer(img);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    //调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgPath);
            out.write(b);
            out.flush();
            out.close();
            HashMap<String, String> map = new HashMap<>();
//        map.put("imgPath", sysLocation + fileName + ".png");
            map.put("code", "20000");
            log.info("html imgPath: " + imgPath);
            return ReturnResultUtils.returnSuccess(map);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("图片上传失败！" + e);
            return ReturnResultUtils.returnFailMsg(508, "上传图片失败");
        }
    }

    @ApiOperation(value = "修改文件内容")
    @PostMapping("/updateFile")
    public ReturnResult updateFile(@RequestBody UpdateFileParam updateFileParam) {
        //System.out.println("updateFileParam = " + updateFileParam);
        updateFileParam.setFilePath(updateFileParam.getFilePath().replace(sysPath, filePaths));
        FileContextReplace.autoReplace(updateFileParam.getFilePath(), updateFileParam.getNewStr());
        return ReturnResultUtils.returnSuccess();
    }

    @ApiOperation(value = "返回富文本内容")
    @GetMapping("/returnHtmlStr")
    public ReturnResult returnHtmlStr(@RequestParam String filePath) {
        String s = null;
        try {
            filePath = filePath.replace(sysPath, filePaths);
            s = FileContextReplace.htmlString(filePath);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return ReturnResultUtils.returnSuccess(s);
    }

}
